package com.yixin.hospital.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yixin.hospital.common.ApiResult;
import com.yixin.hospital.common.Constant;
import com.yixin.hospital.entity.domain.*;
import com.yixin.hospital.entity.dto.req.visit.*;
import com.yixin.hospital.enums.DrugVisitStatusEnum;
import com.yixin.hospital.enums.GuidanceStatusEnum;
import com.yixin.hospital.service.*;
import com.yixin.hospital.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/visit")
@Api(value = "就诊管理", tags = "就诊管理")
public class VisitController {

    @Resource
    private VisitService visitService;
    @Resource
    private VisitSubPackageDrugService visitSubPackageDrugService;
    @Resource
    private VisitSubPackageDrugRealReportService visitSubPackageDrugRealReportService;
    @Resource
    private  VisitPackageDrugService visitPackageDrugService;
    @Resource
    private VisitPackageDrugRealReportService visitPackageDrugRealReportService;
    @Resource
    private VisitHerbalDrugService visitHerbalDrugService;
    @Resource
    private VisitPatientCheckService visitPatientCheckService;
    @Resource
    private GuidanceService guidanceService;


    @PostMapping("/add-visit")
    @ApiOperation(value = "新增就诊")
    @Transactional
    public ApiResult<?> add(@Valid @RequestBody VisitAddReqDTO visitAddReqDTO, HttpServletRequest request) {
        String userName = JwtUtil.getName(request.getHeader(Constant.AUTHORIZATION));
        visitAddReqDTO.getVisit().setCreatedBy(userName);
        visitAddReqDTO.getVisit().setUpdatedBy(userName);
        // 更新状态为 就诊
        Guidance one = guidanceService.getOne(new LambdaQueryWrapper<Guidance>().eq(Guidance::getGuidanceCode, visitAddReqDTO.getVisit().getGuidanceCode()));
        one.setStatus(GuidanceStatusEnum.VISITING.getCode());
        one.setVisitTime(LocalDateTime.now());
        guidanceService.updateById(one);
        return ApiResult.success(visitService.save(visitAddReqDTO.getVisit()));
    }

    @PostMapping("/update-visit-status")
    @ApiOperation(value = "更新就诊状态")
    @Transactional
    public ApiResult<?> updateStatus(@Valid @RequestBody VisitAddReqDTO visitAddReqDTO, HttpServletRequest request) {
        String userName = JwtUtil.getName(request.getHeader(Constant.AUTHORIZATION));
        // 更新状态为 就诊
        Guidance one = guidanceService.getOne(new LambdaQueryWrapper<Guidance>().eq(Guidance::getGuidanceCode, visitAddReqDTO.getGuidanceCode()));
        if(GuidanceStatusEnum.WAITING.getCode().equals(one.getStatus())) {
            one.setStatus(GuidanceStatusEnum.VISITING.getCode());
            one.setVisitTime(LocalDateTime.now());
            one.setUpdatedBy(userName);
            guidanceService.updateById(one);
        }
        return ApiResult.success();
    }


    @GetMapping("/detail-visit")
    @ApiOperation(value = "就诊信息详情")
    public ApiResult<?> detail(@RequestParam("guidanceCode") String guidanceCode) {
        Visit visit = visitService.getOne(new LambdaQueryWrapper<Visit>().eq(Visit::getGuidanceCode, guidanceCode));
        return ApiResult.success(visit);
    }

    @GetMapping("/detail-visit-drug")
    @ApiOperation(value = "查询整装分装记录")
    public ApiResult<?> detailVisitDrug(@RequestParam("guidanceCode") String guidanceCode) {
        List<VisitSubPackageDrug> subPackageDrugList = visitSubPackageDrugService.list(new LambdaQueryWrapper<VisitSubPackageDrug>().eq(VisitSubPackageDrug::getGuidanceCode, guidanceCode));
        VisitSubPackageDrugRealReport subPackageDrugRealReport = visitSubPackageDrugRealReportService.getOne(new LambdaQueryWrapper<VisitSubPackageDrugRealReport>().eq(VisitSubPackageDrugRealReport::getGuidanceCode, guidanceCode));
        List<VisitPackageDrug> packageDrugList = visitPackageDrugService.list(new LambdaQueryWrapper<VisitPackageDrug>().eq(VisitPackageDrug::getGuidanceCode, guidanceCode));
        VisitPackageDrugRealReport packageDrugRealReport = visitPackageDrugRealReportService.getOne(new LambdaQueryWrapper<VisitPackageDrugRealReport>().eq(VisitPackageDrugRealReport::getGuidanceCode, guidanceCode));
        VisitSubPackageDrugReqDTO visitSubPackageDrugReqDTO = new VisitSubPackageDrugReqDTO();
        visitSubPackageDrugReqDTO.setVisitSubPackageDrugList(subPackageDrugList);
        visitSubPackageDrugReqDTO.setVisitSubPackageDrugRealReport(subPackageDrugRealReport);
        visitSubPackageDrugReqDTO.setVisitPackageDrugList(packageDrugList);
        visitSubPackageDrugReqDTO.setVisitPackageDrugRealReport(packageDrugRealReport);
        Visit visit = visitService.getOne(new LambdaQueryWrapper<Visit>().eq(Visit::getGuidanceCode, guidanceCode));
        if (Objects.nonNull(visit)) {
            visitSubPackageDrugReqDTO.setVisit(visit);
            visitSubPackageDrugReqDTO.setStartUsageTime(visit.getStartUsageTime());
            visitSubPackageDrugReqDTO.setEndUsageTime(visit.getEndUsageTime());
        }
        return ApiResult.success(visitSubPackageDrugReqDTO);
    }

    @PostMapping("/add-visit-drug")
    @ApiOperation(value = "新增就诊药品（分装 整装）")
    @Transactional
    public ApiResult<?> addVisitSubPackageDrug(@Valid @RequestBody VisitSubPackageDrugReqDTO visitSubPackageDrugReqDTO, HttpServletRequest request) {
        String userName = JwtUtil.getName(request.getHeader(Constant.AUTHORIZATION));
        // 删除分装未付款药品
        visitSubPackageDrugService.remove(new LambdaQueryWrapper<VisitSubPackageDrug>().eq(VisitSubPackageDrug::getGuidanceCode, visitSubPackageDrugReqDTO.getGuidanceCode()).eq(VisitSubPackageDrug::getStatus, DrugVisitStatusEnum.PENDING.getCode()));
        for (VisitSubPackageDrug visitSubPackageDrug : visitSubPackageDrugReqDTO.getVisitSubPackageDrugList()) {
            visitSubPackageDrug.setVisitId(visitSubPackageDrugReqDTO.getVisitId());
            visitSubPackageDrug.setGuidanceCode(visitSubPackageDrugReqDTO.getGuidanceCode());
            visitSubPackageDrug.setCreatedBy(userName);
            visitSubPackageDrug.setUpdatedBy(userName);
        }
        // 分装药品
        if (!CollectionUtils.isEmpty(visitSubPackageDrugReqDTO.getVisitSubPackageDrugList())) {
            // 只保存未支付处方
            List<VisitSubPackageDrug> pendingList = visitSubPackageDrugReqDTO.getVisitSubPackageDrugList().stream().filter(subPackageDrug -> subPackageDrug.getStatus().equals(DrugVisitStatusEnum.PENDING.getCode())).collect(Collectors.toList());
            visitSubPackageDrugService.saveBatch(pendingList);
        }
        // 分装药品计算表
        visitSubPackageDrugRealReportService.remove(new LambdaQueryWrapper<VisitSubPackageDrugRealReport>().eq(VisitSubPackageDrugRealReport::getGuidanceCode, visitSubPackageDrugReqDTO.getGuidanceCode()));
        visitSubPackageDrugReqDTO.getVisitSubPackageDrugRealReport().setCreatedBy(userName);
        visitSubPackageDrugReqDTO.getVisitSubPackageDrugRealReport().setUpdatedBy(userName);
        visitSubPackageDrugRealReportService.save(visitSubPackageDrugReqDTO.getVisitSubPackageDrugRealReport());

        // 删除整装未付款药品
        visitPackageDrugService.remove(new LambdaQueryWrapper<VisitPackageDrug>().eq(VisitPackageDrug::getGuidanceCode, visitSubPackageDrugReqDTO.getGuidanceCode()).eq(VisitPackageDrug::getStatus, DrugVisitStatusEnum.PENDING.getCode()));
        for (VisitPackageDrug visitPackageDrug : visitSubPackageDrugReqDTO.getVisitPackageDrugList()) {
            visitPackageDrug.setVisitId(visitSubPackageDrugReqDTO.getVisitId());
            visitPackageDrug.setGuidanceCode(visitSubPackageDrugReqDTO.getGuidanceCode());
            visitPackageDrug.setCreatedBy(userName);
            visitPackageDrug.setUpdatedBy(userName);
        }
        // 整装药品
        if(!CollectionUtils.isEmpty(visitSubPackageDrugReqDTO.getVisitPackageDrugList())) {
            // 只保存未支付处方
            List<VisitPackageDrug> pendingList = visitSubPackageDrugReqDTO.getVisitPackageDrugList().stream().filter(packageDrug -> packageDrug.getStatus().equals(DrugVisitStatusEnum.PENDING.getCode())).collect(Collectors.toList());
            visitPackageDrugService.saveBatch(pendingList);
        }
        // 整装药品计算表
        visitPackageDrugRealReportService.remove(new LambdaQueryWrapper<VisitPackageDrugRealReport>().eq(VisitPackageDrugRealReport::getGuidanceCode, visitSubPackageDrugReqDTO.getGuidanceCode()));
        visitSubPackageDrugReqDTO.getVisitPackageDrugRealReport().setCreatedBy(userName);
        visitSubPackageDrugReqDTO.getVisitPackageDrugRealReport().setUpdatedBy(userName);
        visitPackageDrugRealReportService.save(visitSubPackageDrugReqDTO.getVisitPackageDrugRealReport());
        // 就诊信息
        Visit visit = visitService.getOne(new LambdaQueryWrapper<Visit>().eq(Visit::getGuidanceCode, visitSubPackageDrugReqDTO.getGuidanceCode()));
        visit.setDrugMark(visitSubPackageDrugReqDTO.getDrugMark());
        visit.setStartUsageTime(visitSubPackageDrugReqDTO.getStartUsageTime());
        visit.setEndUsageTime(visitSubPackageDrugReqDTO.getEndUsageTime());
        visit.setPlanUsageDays(visitSubPackageDrugReqDTO.getPlanUsageDays());
        visitService.updateById(visit);
        // 修改主记录状态
        Guidance guidance = guidanceService.getOne(new LambdaQueryWrapper<Guidance>().eq(Guidance::getGuidanceCode, visitSubPackageDrugReqDTO.getGuidanceCode()));
        guidance.setStatus(GuidanceStatusEnum.PAYING.getCode());
        guidanceService.updateById(guidance);
        return ApiResult.success();
    }

    @PostMapping("/add-visit-herbal-drug")
    @ApiOperation(value = "新增就诊就诊中草药")
    @Transactional
    public ApiResult<?> addVisitHerbalDrug(@Valid @RequestBody VisitHerbalDrugReqDTO visitHerbalDrugReqDTO, HttpServletRequest request) {
        String userName = JwtUtil.getName(request.getHeader(Constant.AUTHORIZATION));
        for (VisitHerbalDrug visitHerbalDrug : visitHerbalDrugReqDTO.getVisitHerbalDrugList()) {
            visitHerbalDrug.setVisitId(visitHerbalDrugReqDTO.getVisitId());
            visitHerbalDrug.setCreatedBy(userName);
            visitHerbalDrug.setUpdatedBy(userName);
        }
        visitHerbalDrugService.saveBatch(visitHerbalDrugReqDTO.getVisitHerbalDrugList());
        return ApiResult.success();
    }

    @PostMapping("/add-visit-patient-check")
    @ApiOperation(value = "新增就诊患者诊断")
    @Transactional
    public ApiResult<?> addVisitPatientCheck(@Valid @RequestBody VisitPatientCheckReqDTO visitPatientCheckReqDTO, HttpServletRequest request) {
        String userName = JwtUtil.getName(request.getHeader(Constant.AUTHORIZATION));
        for (VisitPatientCheck visitPatientCheck : visitPatientCheckReqDTO.getVisitPatientCheckList()) {
            visitPatientCheck.setVisitId(visitPatientCheckReqDTO.getVisitId());
            visitPatientCheck.setCreatedBy(userName);
            visitPatientCheck.setUpdatedBy(userName);
        }
        visitPatientCheckService.saveBatch(visitPatientCheckReqDTO.getVisitPatientCheckList());
        return ApiResult.success();
    }

}
